package com.xthink.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xthink.common.pojo.polo.*;
import com.xthink.common.result.AjaxResult;
import com.xthink.common.utils.OrderNumberUtils;
import com.xthink.common.vo.pool.InsertPoolVo;
import com.xthink.common.vo.pool.PoolDetailsVo;
import com.xthink.common.vo.pool.PoolListVo;
import com.xthink.common.vo.pool.UpdatePoolVo;
import com.xthink.web.mapper.*;
import com.xthink.web.service.PoolService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PoolServiceImpl extends ServiceImpl<PoolMapper, Pool> implements PoolService {
    @Autowired
    private PoolMapper poolMapper;

    @Autowired
    private PoolAndPackageMapper poolAndPackageMapper;

    @Autowired
    private PoolGroupMapper poolGroupMapper;

    @Autowired
    private PoolPackageMapper poolPackageMapper;

    @Autowired
    private PoolOrderMapper poolOrderMapper;

    //新建流量池
    @Override
    public AjaxResult insertPool(InsertPoolVo insertPoolVo) {
        String[] groupName = insertPoolVo.getGroupName();
        //判断小组名是否重复
        for (String s : groupName) {
            LambdaQueryWrapper<PoolGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PoolGroup::getGroupName, s);
            Integer integer = poolGroupMapper.selectCount(wrapper);
            if (integer != 0) {
                return AjaxResult.error(s + "小组名重复,请重新输入小组名");
            }
        }


        Pool pool = new Pool();
        /*pool.setPoolName(insertPoolVo.getPoolName());
        pool.setPoolType(insertPoolVo.getPoolType());
        pool.setStatus(insertPoolVo.getStatus());*/
        BeanUtils.copyProperties(insertPoolVo, pool);
        int insert = poolMapper.insert(pool);
        if (insert == 0) {
            return AjaxResult.error();
        }
        //不重复则添加小组名
        for (String s : groupName) {
            PoolGroup poolGroup = new PoolGroup();
            poolGroup.setPoolId(pool.getId());
            poolGroup.setGroupName(s);
            poolGroupMapper.insert(poolGroup);
        }
        return AjaxResult.success();
    }

    //流量池编辑数据回显
    @Override
    public AjaxResult updatePoolId(Integer id) {
        Pool pool = poolMapper.selectById(id);
        UpdatePoolVo updatePoolVo = new UpdatePoolVo();
        updatePoolVo.setPoolType(pool.getPoolType());
        updatePoolVo.setPoolName(pool.getPoolName());
        LambdaQueryWrapper<PoolGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PoolGroup::getPoolId, id);
        List<PoolGroup> poolGroups = poolGroupMapper.selectList(wrapper);


        ArrayList<Integer> groupIds = new ArrayList<>();
        ArrayList<String> groupNames = new ArrayList<>();
        for (PoolGroup poolGroup : poolGroups) {
            Integer groupId = poolGroup.getId();
            String groupName = poolGroup.getGroupName();
            groupIds.add(groupId);
            groupNames.add(groupName);
        }
        updatePoolVo.setGroupName((String[]) groupNames.toArray());
        updatePoolVo.setGroupId((Integer[]) groupIds.toArray());
        return AjaxResult.success(updatePoolVo);
    }

    //流量池编辑
    @Override
    public AjaxResult updatePool(UpdatePoolVo updatePoolVo) {
        LambdaUpdateWrapper<Pool> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Pool::getId, updatePoolVo.getPoolId())
                .set(Pool::getPoolType, updatePoolVo.getPoolType())
                .set(Pool::getPoolName, updatePoolVo.getPoolName())
                .set(Pool::getStatus, updatePoolVo.getStatus());
        int update = poolMapper.update(null, wrapper);
        if (update == 0) {
            return AjaxResult.error("修改失败");
        }
        Integer[] groupId = updatePoolVo.getGroupId();
        String[] groupName = updatePoolVo.getGroupName();
        for (int i = 0; i < groupId.length; i++) {

            LambdaUpdateWrapper<PoolGroup> poolGroupLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            poolGroupLambdaUpdateWrapper
                    .eq(PoolGroup::getId, groupId[i])
                    .set(PoolGroup::getGroupName, groupName[i]);
            poolGroupMapper.update(null, poolGroupLambdaUpdateWrapper);
        }


        return AjaxResult.success();
    }

    //分页查询及模糊查询
    @Override
    public AjaxResult poolList(PoolListVo poolListVo) {
        LambdaQueryWrapper<Pool> _wrapper = new LambdaQueryWrapper<>();
        //删除标识
        _wrapper.eq(Pool::getDelFlag, 0);
        List<Pool> pools = poolMapper.selectList(_wrapper);
        for (Pool pool : pools) {

            //当月池总量
            Double PoolQuota = 0.00;
            LambdaQueryWrapper<PoolAndPackage> poolAndPackageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            poolAndPackageLambdaQueryWrapper.eq(PoolAndPackage::getPoolId,pool.getId());
            poolAndPackageLambdaQueryWrapper.eq(PoolAndPackage::getDelFlag,0);
            List<PoolAndPackage> poolAndPackages = poolAndPackageMapper.selectList(poolAndPackageLambdaQueryWrapper);
            for (PoolAndPackage poolAndPackage : poolAndPackages) {
                LambdaQueryWrapper<PoolPackage> poolPackageLambdaQueryWrapper = new LambdaQueryWrapper<>();
                poolPackageLambdaQueryWrapper.eq(PoolPackage::getId,poolAndPackage.getPoolPackageId());
                PoolPackage poolPackage = poolPackageMapper.selectOne(poolPackageLambdaQueryWrapper);
                Double packageSize = poolPackage.getPackageSize();
                PoolQuota = packageSize + PoolQuota;
            }
            //当月累计池用量
            Double PoolConsumption = 0.00;
            //池成员数
            Integer PoolPNumber = 0;
            //卡总数
            Integer PoolCNumber = 0;

            Integer id = pool.getId();
            LambdaQueryWrapper<PoolGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PoolGroup::getPoolId, id);
            List<PoolGroup> poolGroups = poolGroupMapper.selectList(wrapper);

            for (PoolGroup poolGroup : poolGroups) {
                /*Double groupQuota = poolGroup.getQuota();
                PoolQuota = groupQuota + PoolQuota;*/

                Double groupConsumption = poolGroup.getGroupConsumption();
                PoolConsumption = groupConsumption + PoolConsumption;

                Integer pNumber = poolGroup.getPNumber();
                PoolPNumber = pNumber + PoolPNumber;

                Integer cNumber = poolGroup.getCNumber();
                PoolCNumber = cNumber + PoolCNumber;
            }
            //池内小组数
            Integer PoolGroup = poolGroupMapper.selectCount(wrapper);

            //修改对应池数据
            LambdaUpdateWrapper<Pool> poolLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            poolLambdaUpdateWrapper.eq(Pool::getId, id)
                    .set(Pool::getPoolTotal, PoolQuota)
                    .set(Pool::getPoolConsumption, PoolConsumption)
                    .set(Pool::getPoolMember, PoolPNumber)
                    .set(Pool::getPoolGroup, PoolGroup)
                    .set(Pool::getPoolTotal, PoolCNumber);
            //提交修改
            poolMapper.update(null, poolLambdaUpdateWrapper);
        }


        LambdaQueryWrapper<Pool> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(poolListVo.getPoolName()), Pool::getPoolName, poolListVo.getPoolName());
        wrapper.eq(poolListVo.getDate() != null, Pool::getCreateTime, poolListVo.getDate());
        wrapper.eq(poolListVo.getDate() != null, Pool::getUpdateTime, poolListVo.getDate());
        wrapper.eq(poolListVo.getStatus() != null, Pool::getStatus, poolListVo.getStatus());

        //删除标识
        wrapper.eq(Pool::getDelFlag, 0);

        Page<Pool> _page = new Page<>(poolListVo.getPage(), poolListVo.getSize());
        Page<Pool> page = poolMapper.selectPage(_page, wrapper);
        List<Pool> records = page.getRecords();

        if (records.size() == 0) {
            return AjaxResult.error("未搜索到此流量池");
        }
        return AjaxResult.success(records);
    }

    //上架
    @Override
    public AjaxResult putOnPool(Integer[] ids) {
        for (Integer id : ids) {
            LambdaUpdateWrapper<Pool> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Pool::getId, id).set(Pool::getStatus, 1);
            int update = poolMapper.update(null, wrapper);
            if (update == 0) {
                return AjaxResult.error("ID:" + id + ",池列表上架失败");
            }
        }
        return AjaxResult.success();
    }

    //下架
    @Override
    public AjaxResult putOffPool(Integer[] ids) {
        for (Integer id : ids) {
            LambdaUpdateWrapper<Pool> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Pool::getId, id).set(Pool::getStatus, 0);
            int update = poolMapper.update(null, wrapper);
            if (update == 0) {
                return AjaxResult.error("ID:" + id + ",池列表下架失败");
            }
        }
        return AjaxResult.success();
    }

    //删除池列表
    @Override
    public AjaxResult deletePool(Integer[] ids) {
        for (Integer id : ids) {
            LambdaUpdateWrapper<Pool> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Pool::getId, id).set(Pool::getDelFlag, 1);
            int update = poolMapper.update(null, wrapper);
            if (update == 0) {
                return AjaxResult.error("ID:" + id + ",池列表删除失败");
            }
        }
        return AjaxResult.success();
    }

    //池详情
    @Override
    public AjaxResult detailsPool(Integer id) {
        PoolDetailsVo poolDetailsVo = new PoolDetailsVo();
        //假设该流量池未购买叠加包或者主套餐 所以先设置主套餐和叠加包都为0
        poolDetailsVo.setMainstreamVolume(0.00);
        poolDetailsVo.setSuperimposedFlow(0.00);
        LambdaQueryWrapper<PoolAndPackage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PoolAndPackage::getPoolId, id);
        List<PoolAndPackage> poolAndPackages = poolAndPackageMapper.selectList(wrapper);
        for (PoolAndPackage poolAndPackage : poolAndPackages) {
            Integer poolPackageId = poolAndPackage.getPoolPackageId();
            PoolPackage poolPackage = poolPackageMapper.selectById(poolPackageId);
            Integer packageType = poolPackage.getPackageType();
            //等于0就是主套餐
            if (packageType == 0) {
                poolDetailsVo.setMainstreamVolume(poolPackage.getPackageSize());
            }
            //等于1就是叠加包
            if (packageType == 1) {
                poolDetailsVo.setSuperimposedFlow(poolPackage.getPackageSize());
            }
        }

        //设置流量池类型 计算总量 获取已用流量 计算剩余流量
        Pool pool = poolMapper.selectById(id);
        poolDetailsVo.setPoolType(pool.getPoolType());
        poolDetailsVo.setTotal(poolDetailsVo.getMainstreamVolume() + poolDetailsVo.getSuperimposedFlow());
        poolDetailsVo.setPoolConsumption(pool.getPoolConsumption());
        poolDetailsVo.setResidualFlow(poolDetailsVo.getTotal() - poolDetailsVo.getPoolConsumption());
        return AjaxResult.success(poolDetailsVo);
    }

    //绑定池套餐
    @Override
    public AjaxResult binDingPoolPackage(Integer[] poolIds, Integer poolPackageId) {

        for (Integer poolId : poolIds) {
            PoolAndPackage poolAndPackage = new PoolAndPackage();
            poolAndPackage.setPoolId(poolId);
            poolAndPackage.setPoolPackageId(poolPackageId);
            int insert = poolAndPackageMapper.insert(poolAndPackage);
            if (insert == 0) {
                return AjaxResult.error("流量池ID:" + poolId + "绑定套餐失败");
            }

            //生成池订单
            PoolPackage poolPackage = poolPackageMapper.selectById(poolPackageId);
            PoolOrder poolOrder = new PoolOrder();
            poolOrder.setOrderNumber(OrderNumberUtils.getCTCNumber());
            poolOrder.setPoolId(poolId);
            poolOrder.setPoolName(poolMapper.selectById(poolId).getPoolName());
            poolOrder.setPackageName(poolPackage.getPackageName());
            poolOrder.setSaleName(poolPackage.getSaleName());
            poolOrder.setPackageType(poolPackage.getPackageType());
            poolOrder.setPackageSize(poolPackage.getPackageSize());
            poolOrder.setPackagePrice(poolPackage.getPackagePrice());
            //添加进池订单
            poolOrderMapper.insert(poolOrder);
            //修改池套餐字段
            Pool pool = poolMapper.selectById(poolId);
            String poolPackageName = pool.getPoolPackage();
            LambdaUpdateWrapper<Pool> poolLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            if (poolPackageName == null) {
                poolLambdaUpdateWrapper.eq(Pool::getId, poolId).set(Pool::getPoolPackage, poolPackage.getPackageName());
            } else {
                poolLambdaUpdateWrapper.eq(Pool::getId, poolId).set(Pool::getPoolPackage, poolPackageName + " / " + poolPackage.getPackageName());
            }
            poolMapper.update(null, poolLambdaUpdateWrapper);
        }
        return AjaxResult.success();
    }

    //解绑池套餐
    @Override
    public AjaxResult unBinDingPoolPackage(Integer[] poolIds, Integer poolPackageId) {


        for (Integer poolId : poolIds) {

            LambdaUpdateWrapper<PoolAndPackage> poolAndPackageLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            poolAndPackageLambdaUpdateWrapper
                    .eq(PoolAndPackage::getPoolPackageId, poolPackageId)
                    .eq(PoolAndPackage::getPoolId,poolId)
                    .set(PoolAndPackage::getDelFlag, 1);
            int update = poolAndPackageMapper.update(null, poolAndPackageLambdaUpdateWrapper);
            if (update == 0) {
                return AjaxResult.error("ID:" + poolId + "解绑失败");
            }

            //解绑后修改对应流量池 字段 池套餐
            LambdaQueryWrapper<PoolAndPackage> poolAndPackageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            poolAndPackageLambdaQueryWrapper.eq(PoolAndPackage::getPoolId,poolId);
            poolAndPackageLambdaQueryWrapper.eq(PoolAndPackage::getDelFlag,0);
            List<PoolAndPackage> poolAndPackages = poolAndPackageMapper.selectList(poolAndPackageLambdaQueryWrapper);

            String packageNames = "";
            for (int i = 0; i < poolAndPackages.size(); i++) {
                PoolAndPackage poolAndPackage = poolAndPackages.get(i);
                PoolPackage poolPackage = poolPackageMapper.selectById(poolAndPackage.getPoolPackageId());
                String packageName = poolPackage.getPackageName();
                if (i==0){
                    packageNames = packageName;
                }else {
                    packageNames = packageNames + "  " + packageName;
                }
            }
            LambdaUpdateWrapper<Pool> poolLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            poolLambdaUpdateWrapper.eq(Pool::getId,poolId).set(Pool::getPoolPackage,packageNames);
            poolMapper.update(null,poolLambdaUpdateWrapper);

        }
        return AjaxResult.success();
    }


}
